﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace XMM.Dialoges.Library
{
    /// <summary>
    /// Interaktionslogik für ImportFile.xaml
    /// </summary>
    public partial class ImportFile : Window
    {
        XMM.Library ParentLibrary { get; set; }

        System.IO.FileInfo SelectedFile { get; set; }
        Objects.MediaInfo SelectedMediaInfo { get; set; }

        int MediaType { get; set; }

        Mutex mutPrefetchShows = new Mutex();

        bool IsPrefetching { get; set; }

        ObservableCollection<Objects.Series> _AvailableSeries = new ObservableCollection<Objects.Series>();

        public ObservableCollection<Objects.Series> AvailableSeries { get { return _AvailableSeries; } }

        public ImportFile(XMM.Library dlgParentLibrary)
        {
            InitializeComponent();

            ParentLibrary = dlgParentLibrary;
            MediaType = 1;
            startPrefetchShows();
        }

        private void btnBrowseFile_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlgBrowseFile = new System.Windows.Forms.OpenFileDialog();

            grdMediaDetails.Children.Clear();
            SelectedFile = null;

            if (dlgBrowseFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SelectedFile = new System.IO.FileInfo(dlgBrowseFile.FileName);
                SelectedMediaInfo = new Objects.MediaInfo();
                SelectedMediaInfo.FullPath = SelectedFile.FullName;
                SelectedMediaInfo.MediaType = MediaType;
                SelectedMediaInfo.FileName = SelectedFile.Name;
                SelectedMediaInfo.DirectoryName = SelectedFile.DirectoryName;

                if (SelectedFile != null)
                {
                    txtSelectedFile.Text = SelectedFile.FullName;
                    grdMediaDetails.IsEnabled = true;

                    switch (MediaType)
                    {
                        case 1:
                            Controls.Library.Import_Movie ctlMovie = new Controls.Library.Import_Movie(SelectedMediaInfo);
                            grdMediaDetails.Children.Add(ctlMovie);
                            break;
                        case 2:
                            Controls.Library.Import_Episode ctlEpisode = new Controls.Library.Import_Episode(this, SelectedMediaInfo);
                            grdMediaDetails.Children.Add(ctlEpisode);
                            break;
                    }
                }
            }
            else
            {
                grdMediaDetails.IsEnabled = false;
            }
        }

        private void rdbMovie_Checked(object sender, RoutedEventArgs e)
        {
            MediaType = 1;

            if (SelectedMediaInfo != null)
            {
                SelectedMediaInfo.MediaType = 1;

                grdMediaDetails.Children.Clear();
                Controls.Library.Import_Movie ctlMovie = new Controls.Library.Import_Movie(SelectedMediaInfo);
                grdMediaDetails.Children.Add(ctlMovie);
            }
        }

        private void rdbShow_Checked(object sender, RoutedEventArgs e)
        {
            MediaType = 2;

            if (SelectedMediaInfo != null)
            {
                SelectedMediaInfo.MediaType = 2;

                grdMediaDetails.Children.Clear();
                Controls.Library.Import_Episode ctlEpisode = new Controls.Library.Import_Episode(this, SelectedMediaInfo);
                //ctlEpisode.
                grdMediaDetails.Children.Add(ctlEpisode);
            }
        }

        public void startPrefetchShows()
        {
            // Prefetch Shows
            Thread thPrefetchShows = new Thread(new ThreadStart(prefetchShows));
            thPrefetchShows.Start();
        }

        /// <summary>
        /// Prefetch Shows.
        /// </summary>
        private void prefetchShows()
        {
            if (mutPrefetchShows.WaitOne(500))
            {
                IsPrefetching = true;
                //Dispatcher.Invoke(new updateStatusCallback(updateStatus), new object[] { 0, "Lade verfügbare Serien..." });
                _AvailableSeries = new ObservableCollection<Objects.Series>();
                List<Objects.Series> lSeries = Objects.Series.getAllSeries();

                int iShowPercentage = 0;
                if (lSeries.Count != 0)
                    iShowPercentage = (int)Math.Round(((decimal)100 / lSeries.Count), 0);

                int iCurrentShow = 1;

                if (lSeries != null && lSeries.Count > 0)
                {
                    foreach (Objects.Series oSeries in lSeries)
                    {
                        int iCurrentPercentage = iCurrentShow * iShowPercentage;
                        if (iCurrentPercentage > 100)
                            iCurrentPercentage = 100;

                        //Dispatcher.Invoke(new updateStatusCallback(updateStatus), new object[] { iCurrentPercentage, "Lade Serie " + iCurrentShow.ToString() + " of " + lSeries.Count.ToString() + "..." });
                        _AvailableSeries.Add(oSeries);

                        ++iCurrentShow;
                    }
                }

                //Dispatcher.Invoke(new updateStatusCallback(updateStatus), new object[] { 0, "Bereit..." });
                IsPrefetching = false;

                // Release Prefetch-Mutex.
                mutPrefetchShows.ReleaseMutex();
            }
        }

        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            switch (MediaType)
            {
                case 1:
                    ImportMovie();
                    break;
                case 2:
                    ImportEpisode();
                    break;
            }
        }

        private void ImportMovie()
        {
            if (SelectedMediaInfo != null && SelectedMediaInfo.MediaType == 1)
            {
                Controls.Library.Import_Movie ctlImportMovie = (Controls.Library.Import_Movie)grdMediaDetails.Children[0];
                //Objects.Movie oNewMovie = (Objects.Movie)SelectedMediaInfo.UserdefinedMediaInfo;
                Objects.Movie oNewMovie = ctlImportMovie.getCurrentData;

                if (oNewMovie.Name != String.Empty && oNewMovie.Files.Count > 0)
                {
                    if (oNewMovie.SaveNew())
                    {
                        try
                        {
                            Settings oSettings = new Settings();
                            string sCoverImagePath = ctlImportMovie.ctlCoverArt.CoverImagePath;
                            if (sCoverImagePath != String.Empty && System.IO.File.Exists(sCoverImagePath))
                            {
                                System.Drawing.Bitmap bmpCoverImage = new System.Drawing.Bitmap(ctlImportMovie.ctlCoverArt.CoverImagePath);
                                System.Drawing.Bitmap bmpCoverThumb = Functions.Imaging.ResizeBitmap(bmpCoverImage, (int)(bmpCoverImage.Width / 10), (int)(bmpCoverImage.Height / 10));
                                bmpCoverImage.Save(oSettings.LibraryDataStorage + "movies\\images\\xmm_" + SelectedFile.Name + ".jpg");
                                bmpCoverThumb.Save(oSettings.LibraryDataStorage + "movies\\thumb\\xmm_" + SelectedFile.Name + ".jpg");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Fehler beim Speichern des Cover-Bildes: " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    ParentLibrary.RefreshXMM();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Unvollständige Angaben!");
                }
            }
        }

        private void ImportEpisode()
        {
            if (SelectedMediaInfo != null && SelectedMediaInfo.MediaType == 2)
            {
                Controls.Library.Import_Episode ctlImportEpisode = (Controls.Library.Import_Episode)grdMediaDetails.Children[0];

                Objects.SeriesEpisode oNewEpisode = ctlImportEpisode.CurrentData;

                if (oNewEpisode.SeriesID > 0 && oNewEpisode.SeasonID > 0 && oNewEpisode.EpisodeNo > 0 && oNewEpisode.MediaFile != String.Empty)
                {
                    Objects.SeriesSeason oSeason = new Objects.SeriesSeason(oNewEpisode.SeasonID);

                    if (oSeason.BaseDirectory != String.Empty)
                    {
                        if (MessageBox.Show("Möchten Sie die Datei in das Basisverzeichnis (\"" + oSeason.BaseDirectory + "\") der Staffel verschieben?", "Datei verschieben?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            try
                            {
                                System.IO.FileInfo fiMediaFile = new System.IO.FileInfo(oNewEpisode.MediaFile);
                                System.IO.File.Move(oNewEpisode.MediaFile, oSeason.BaseDirectory + fiMediaFile.Name);
                                oNewEpisode.MediaFile = oSeason.BaseDirectory + fiMediaFile.Name;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Die Datei \"" + oNewEpisode.MediaFile + "\" konnte nicht verschoben werden: " + ex.Message + Environment.NewLine + Environment.NewLine + "Import abgebrochen!", "Fehler beim Verschieben", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }
                    }

                    oNewEpisode.SaveNew();
                    ParentLibrary.RefreshXMM();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Unvollständige Angaben!");
                }
            }
        }
    }
}
